import json

from utils.file_api import save_to_file
from utils.api_client import APIClient
from utils.test_case import generate_test_cases, generate_erlang_cases, generate_document_completion, generate_json_test_cases
from utils.xmind_trans import gen_xmind

from openpyxl import load_workbook

import pandas as pd


def generate(input_file_path=None):
    if input_file_path is None:
        with open("config/settings.json", "r") as f:
            input_file_path = eval(f.read())["input_file_path"]

    with open("config/settings.json", "r") as f:
        api_type = eval(f.read())["api_type"]
        api_url = eval(f.read())["api_url"]
        api_key = eval(f.read())["api_key"]
    api_client = APIClient(api_key=api_key, base_url=api_url, api_type=api_type)
    all_sheets = pd.read_excel(input_file_path, sheet_name=None)
    datas = []
    # 提取出有数据的部分
    for sheet_name, df in all_sheets.items():
        for i in range(len(df)):
            for col in df.columns:
                value = df.at[i, col]
                if not pd.isna(value):
                    datas.append(value)
    # print(datas)
    # 保存文档内容
    pick_file_path = input_file_path.split('.')[0] + ".txt"
    with open(pick_file_path, "w", encoding="utf-8") as f:
        f.write("\n".join(datas))
    # 生成测试用例
    test_cases = generate_test_cases(api_client, datas)
    # 生成erlang接口用例
    erlang_cases = generate_erlang_cases(api_client, datas)

    replaced_file_name = input_file_path.split('.')[0].replace('input', 'output')
    # 保存输出文件
    save_to_file(replaced_file_name + "_generate.md", test_cases)

    # save_to_file(replaced_file_name + "_generate_trans.md", text_trans(test_cases))
    # 保存erlang接口用例
    save_to_file(replaced_file_name + "_generate_erlang.md", erlang_cases)

    print(f"测试用例已生成并保存至: {replaced_file_name}")


def generate_on_api(config, callback_func):
    input_file_path = config["input_file_path"]
    gen_test_case = config.get("gen_test_case", False)
    gen_erl_case = config.get("gen_erl_case", False)
    gen_document_case = config.get("gen_document_case", False)
    gen_json_case = config.get("gen_json_case", False)
    api_client = APIClient(api_key=config["api_key"], base_url=config["api_url"], api_type=["api_type"])
    all_sheets = {}
    try:
        all_sheets = pd.read_excel(input_file_path, sheet_name=None, engine='openpyxl')
    except Exception as e:
        print("load excel error:", e)
        # print("try load book")
        try:
            wb = load_workbook(input_file_path, data_only=True, read_only=True)
            # print("load book finish")
            for sheet_name, ws in wb.worksheets.items():
                data = []
                for row in ws.iter_rows(values_only=True):
                    data.append(row)
                indf = pd.DataFrame(data)
                all_sheets[sheet_name] = indf
        except Exception as e:
            print("load book error22222:", e)
            return

    datas = []
    # 提取出有数据的部分
    for sheet_name, df in all_sheets.items():
        for i in range(len(df)):
            for col in df.columns:
                value = df.at[i, col]
                if not pd.isna(value):
                    datas.append(str(value))
    # print(datas)
    # 保存文档内容
    pick_file_path = input_file_path.split('.')[0] + ".txt"
    with open(pick_file_path, "w", encoding="utf-8") as f:
        f.write("\n".join(datas))

    replaced_file_name = input_file_path.split('.')[0].replace('input', 'output')

    # 生成测试用例
    if gen_test_case:
        callback_func("test_cases")
        test_cases = generate_test_cases(api_client, datas)
        # 保存输出文件
        save_to_file(replaced_file_name + "_generate.md", test_cases)

    # 生成erlang接口用例
    if gen_erl_case:
        callback_func("erlang_cases")
        erlang_cases = generate_erlang_cases(api_client, datas)
        # 保存erlang接口用例
        save_to_file(replaced_file_name + "_generate_erlang.md", erlang_cases)

    if gen_document_case:
        callback_func("document_completion")
        document_cases = generate_document_completion(api_client, datas)
        # 保存输出文档
        save_to_file(replaced_file_name + "_generate_document.md", document_cases)
    if gen_json_case:
        callback_func("json_cases")
        str_cases = generate_json_test_cases(api_client, datas)
        # 保存输出文档
        # save_to_file(replaced_file_name + "_generate.json", str_cases)
        if isinstance(str_cases, str):
            # 字符串需要转json
            try:
                json_data = json.loads(str_cases)
            except json.JSONDecodeError:
                json_data = str_cases
        else:
            json_data = str_cases
        gen_xmind(replaced_file_name + "_generate.xmind", json_data)

    # save_to_file(replaced_file_name + "_generate_trans.md", text_trans(test_cases))

    print(f"测试用例已生成并保存至: {replaced_file_name}")


